//
//  ActionsCollectionView.swift
//  home
//
//  Created by Yun Zeng on 2019/8/7.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

// 动作关联的服务集合
class ActionsCollectionView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    var manager: ActionsServiceManager
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var title: String = "此场景将执行以下动作"
    fileprivate var actionsView: UICollectionView!
    
    init(frame: CGRect, manager: ActionsServiceManager, title: String? = nil) {
        self.manager = manager
        super.init(frame: frame)
        
        if title != nil {
            self.title = title!
        }
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        layout.itemSize = CGSize(width: 105, height: 105)
        
        if title != nil {
            layout.headerReferenceSize = CGSize(width: 200, height: 32)
        } else {
            layout.headerReferenceSize = CGSize(width: 0, height: 0)
        }
        
        layout.minimumInteritemSpacing = 0.0
        layout.minimumLineSpacing = 13.0
        layout.estimatedItemSize = CGSize(width: 0, height: 0)
        
        actionsView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        actionsView.dataSource = self
        actionsView.delegate = self
        
        self.addSubview(self.actionsView)
        actionsView.delaysContentTouches = false
        actionsView.translatesAutoresizingMaskIntoConstraints = false
        actionsView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
        actionsView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        actionsView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        actionsView.heightAnchor.constraint(equalToConstant: 500).isActive = true
        
        actionsView.register(ActionServiceCell.self, forCellWithReuseIdentifier: ActionServiceCell.identifier)
        actionsView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ActionsCollectionView.identifier)
        actionsView.backgroundColor = UIColor.clear
        actionsView.delaysContentTouches = false
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.manager.services.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ActionServiceCell.identifier, for: indexPath as IndexPath) as! ActionServiceCell
        cell.setService(service: self.manager.services[indexPath.row])
        return cell
    }
    
    // 表头
    static let identifier = "ScenesCollectionViewHeader"
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableView: UICollectionReusableView!
        if kind == UICollectionView.elementKindSectionHeader {
            reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ActionsCollectionView.identifier, for: indexPath)
            
            let color = UIColor(red: 98/255, green: 98/255, blue: 98/255, alpha: 1)
            let xOffset = 23
            
            let label = UILabel(frame: CGRect(x: xOffset, y: 0, width: Int(collectionView.bounds.width), height: 20))
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),
                NSAttributedString.Key.kern: -0.86,
                NSAttributedString.Key.foregroundColor: color]
            label.attributedText = NSAttributedString(string: self.title, attributes: attributes)
            label.textAlignment = NSTextAlignment.left
            reusableView.addSubview(label)
            // 文字阴影，让字体显得更白
            reusableView.layer.shadowColor = UIColor(red: 103/255, green: 103/255, blue: 103/255, alpha: 0.32).cgColor
            reusableView.layer.shadowOffset = CGSize.zero
            reusableView.layer.shadowRadius = 3.0
            reusableView.layer.shadowOpacity = 0.0
        }
        return reusableView
    }
}

// 动作单元格
class ActionServiceCell: UICollectionViewCell {
    
    var action: ((_ service: ServiceCell) -> Void)?
    var serviceView: ServiceCellView!
    static let identifier = "ActionServiceIdentifier"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        let rect = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        self.serviceView = ServiceCellView(frame: rect)
        self.addSubview(self.serviceView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setService(service: ServiceCellDelegate) {
        if service.name != self.serviceView.name {
            self.serviceView.name = service.name
        }
        
        if service.room != self.serviceView.room {
            self.serviceView.room = service.room
        }
        
        if service.icon != self.serviceView.iconView {
            self.serviceView.iconView = service.icon
        }
        
        // 动作描述临时解决方案
        var desc = service.desc
        if desc == "关" {
            desc = "关掉"
        } else if desc == "开" {
            desc = "打开"
        }
        if desc != self.serviceView.desc {
            self.serviceView.desc = desc
        }
        
        if service.state != self.serviceView.state {
            self.serviceView.state = service.state
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        UIView.animate(withDuration: 0.1) {
                self.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if let touch = touches.first {
            let rate = touch.force / touch.maximumPossibleForce
            let scaling = 1.0 + (rate / 2) + 0.3
            UIView.animate(withDuration: 0.1, animations: {
                self.transform = CGAffineTransform(scaleX: scaling, y: scaling)
            })
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10.0, options: [], animations: {
            self.transform = .identity
        })
    }
}



